package com.gitee.mazhenggg.mall.account.web.controller;

import com.gitee.mazhenggg.mall.account.domain.type.Money;
import com.gitee.mazhenggg.mall.account.domain.type.UserId;
import com.gitee.mazhenggg.mall.account.web.service.AccountService;
import com.gitee.mazhenggg.mall.account.web.service.PointProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping(value = "/api/account")
public class AccountController {

    @Autowired
    AccountService accountService;
    @Autowired
    PointProvider pointProvider;

    @GetMapping("/available/{userId}")
    public Long getAccountByUserId(@PathVariable Long userId){
        Money available = accountService.getAccountByUserId(new UserId(userId));
        return available.getValue();
    }

    @PostMapping("/consume")
    @Transactional
    public String consume(@RequestBody Map<String, Long> consume){
        if(consume.get("userId")==null||consume.get("amount")==null){
            return "fail";
        }
        accountService.consumeByUserId(new UserId(consume.get("userId")),new Money(consume.get("amount")));
        pointProvider.addPoint(consume);
        return "success";
    }
}
